import Carousel from './Carousel';
import './css/sider.scss';

class Slider extends Carousel {
  constructor(el, { defaultIndex, duration }) {
    super(el);
    this.$imgStage = this.$el.getElementsByClassName('img-stage')[0];
    this.duration = duration;
    this._index = defaultIndex;
    this.imgWidth = this.$imgWraps[0].offsetWidth;
    this.init();
  }

  // static timer = null;

  get currentIndex() {
    return this._index;
  }

  set currentIndex(val) {
    this.update(() => {
      this._index = val;
    });
  }

  init() {
    //无缝切换的第一步是将第一张图复制并放入到最后
    this.clone();
    this.update(null, true);
    this.bindEvent();
    this.autoPlay();
  }

  clone() {
    //深拷贝一份节点
    const clonedNode = this.$imgWraps[0].cloneNode(true);
    this.$imgStage.appendChild(clonedNode);
  }

  slide() {
    //瞬间回到第一张图片时是没有过渡效果
    this.$imgStage.style.transition = 'transform .3s';
    this.$imgStage.style.transform = `translate3d(${
      -this.currentIndex * this.imgWidth
    }px, 0, 0)`;
  }

  reset() {
    /**
     * 保持异步的原因是此时有两个任务是异步执行的
     * 500 > .3s
     */
    setTimeout(() => {
      //第一个任务是最后一张回到第一张是没有动画的
      this.$imgStage.style.transition = 'none';
      //第二个任务是第一张轮播至第二张
      this.$imgStage.style.transform = 'translate3d(0, 0, 0)';
    }, 500);
  }

  autoPlay() {
    this.timer = setInterval(() => {
      this.currentIndex++;
      this.slide();
      //走到最后一张时恢复至第一张
      if (this.currentIndex >= this.$imgWraps.length - 1) {
        this.currentIndex = 0;
        this.reset();
      }
    }, this.duration);
  }

  handleMouseEnter() {
    clearInterval(this.timer);
  }

  handleMouseLeave() {
    this.autoPlay();
  }

  handleDotClick(e) {
    const tar = e.target;
    if (tar.className === 'dot') {
      //通过操作index可以实现轮播图的切换
      this.currentIndex = [].indexOf.call(this.$dots, tar);
      this.slide();
    }
  }

  update(setIndex, isInitial) {
    let currentIdx;
    if (!isInitial) {
      currentIdx =
        this.currentIndex >= this.$imgWraps.length - 1 ? 0 : this.currentIndex;
      this.$dots[currentIdx].classList.remove('active');
      setIndex();
    }
    currentIdx =
      this.currentIndex >= this.$imgWraps.length - 1 ? 0 : this.currentIndex;
    this.$dots[currentIdx].classList.add('active');
  }
}

export default Slider;
